const Crypto = require("./crypto.js");
const Hmac = require("./hmac.js");
const Sha1 = require("./sha1.js");
const Base64 = require("./base64.js");
const config = require("../config/index.js");
console.log(config);

class Upload {
  defaultOption = {
    size:20,//默认20M,
    timeout: 87600,
    OSSAccessKeyId: config.IMAGE_OSS_ACCESS_ID,
    AccessKeySecret: config.IMAGE_OSS_ACCESS_SECRET
  }
  
  constructor(option = {}){
    this.defaultOption = Object.assign(this.defaultOption,option);
    console.log(this.defaultOption)
  }
  getPolicyBase64 = function () {
    let date = new Date();
    date.setHours(date.getHours() + this.defaultOption.timeout);
    
    let srcT = date.toISOString();
    const policyText = {
      "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
      "conditions": [
        ["content-length-range", 0, this.defaultOption.size * 1024 * 1024] // 设置上传文件的大小限制,5mb
      ]
    };
    console.log(policyText);
    const policyBase64 = Base64.encode(JSON.stringify(policyText));
    return policyBase64;
  }
  getSignature = function (policyBase64) {
    const accesskey = this.defaultOption.AccessKeySecret;

    const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
      asBytes: true
    });
    const signature = Crypto.util.bytesToBase64(bytes);

    return signature;
  }
  generateConfig(){
    let policyBase64 = this.getPolicyBase64();
    let signature = this.getSignature(policyBase64);
    return {
      success_action_status:'200',
      signature,
      policy: policyBase64,
      OSSAccessKeyId: this.defaultOption.OSSAccessKeyId
    }
  }
};
module.exports = Upload;